<script lang="ts" setup>
import { getRuleListAPI } from '@/apis/car';
import type { Rule, RuleListParams } from '@/types/car';
import { ref } from 'vue';
import { utils, writeFileXLSX } from 'xlsx';
import { ElMessageBox, ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElSelect, ElOption } from 'element-plus';

const ruleList = ref<Rule[]>([]);
const params = ref<RuleListParams>({
  page: 1,
  pageSize: 10
});
const total = ref(0);

const getRuleList = async () => {
  const res = await getRuleListAPI(params.value);
  ruleList.value = res.data.rows;
  total.value = res.data.total;
};
getRuleList();

// 时长收费:duration, 按次收费:turn, 分段收费:partition
const chargeTypeMap = new Map<Rule['chargeType'], string>([
  ['duration', '时长收费'],
  ['turn', '按次收费'],
  ['partition', '分段收费']
]);

// 导出Excel
const exportToExcel = () => {
  const workbook = utils.book_new();
  const worksheet = utils.json_to_sheet(ruleList.value.map((item, index) => ({
    ...item,
    id: index + 1,
    chargeType: chargeTypeMap.get(item.chargeType)
  })));
  utils.book_append_sheet(workbook, worksheet, '计费规则');
  utils.sheet_add_aoa(
    worksheet,
    [
      ['序号', '计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上限(元)', '计费方式', '计费规则'],
    ],
    { origin: 'A1' }
  );
  writeFileXLSX(workbook, '停车计费规则.xlsx');
};

// 删除规则
const deleteRule = (index: number) => {
  ruleList.value.splice(index, 1);
  ElMessage.success('删除成功');
};

// 确认删除
const confirmDelete = (index: number) => {
  ElMessageBox.confirm('确定要删除该计费规则吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteRule(index);
  }).catch(() => {
    // 取消删除
  });
};

// 对话框显示控制
const dialogVisible = ref(false);

// 表单数据
const form = ref<{
  id: number | null;
  ruleNumber: string;
  ruleName: string;
  freeDuration: number;
  chargeCeiling: number;
  chargeType: Rule['chargeType'];
  ruleNameView: string;
}>({
  id: null,
  ruleNumber: '',
  ruleName: '',
  freeDuration: 0,
  chargeCeiling: 0,
  chargeType: 'duration', // 修改这里，初始化为一个合法值
  ruleNameView: ''
});
// 表单验证规则
const rules = ref({
  ruleNumber: [{ required: true, message: '请输入计费规则编号', trigger: 'blur' }],
  ruleName: [{ required: true, message: '请输入计费规则名称', trigger: 'blur' }],
  freeDuration: [{ required: true, message: '请输入免费时长', trigger: 'blur' }],
  chargeCeiling: [{ required: true, message: '请输入收费上限', trigger: 'blur' }],
  chargeType: [
    { required: true, message: '请选择计费方式', trigger: 'change' },
    { validator: (rule, value, callback) => {
      if (!['duration', 'turn', 'partition'].includes(value)) {
        callback(new Error('请选择一个有效的计费方式'));
      } else {
        callback();
      }
    }, trigger: 'change' }
  ],
  ruleNameView: [{ required: true, message: '请输入计费规则', trigger: 'blur' }]
});


// 提交表单
const submitForm = () => {
  const newRule: Rule = {
    ...form.value,
    id: Date.now(), // 使用时间戳作为唯一ID
  };
  ruleList.value.push(newRule);
  dialogVisible.value = false;
  ElMessage.success('添加成功');
};

// 提交表单并验证
const validateForm = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      submitForm();
    } else {
      ElMessage.error('请填写完整信息');
      // 移除 return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  form.value = {
    ruleNumber: '',
    ruleName: '',
    freeDuration: 0,
    chargeCeiling: 0,
    chargeType: '',
    ruleNameView: ''
  };
  formRef.value?.resetFields();
};

// 表单实例
const formRef = ref<InstanceType<typeof ElForm>>();
</script>

<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="dialogVisible = true">增加停车计费规则</el-button>
      <el-button @click="exportToExcel()">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上限(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="{ row }">
            {{ chargeTypeMap.get(row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" width="320" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ $index }">
            <el-button size="small" type="primary" link>编辑</el-button>
            <el-button size="small" type="primary" link @click="confirmDelete($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 对话框 -->
    <el-dialog v-model="dialogVisible" title="增加停车计费规则" width="40%" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="计费规则编号" prop="ruleNumber">
          <el-input v-model="form.ruleNumber" />
        </el-form-item>
        <el-form-item label="计费规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" />
        </el-form-item>
        <el-form-item label="免费时长(分钟)" prop="freeDuration">
          <el-input v-model.number="form.freeDuration" />
        </el-form-item>
        <el-form-item label="收费上限(元)" prop="chargeCeiling">
          <el-input v-model.number="form.chargeCeiling" />
        </el-form-item>
        <el-form-item label="计费方式" prop="chargeType">
          <el-select v-model="form.chargeType" placeholder="请选择计费方式">
            <el-option label="时长收费" value="duration" />
            <el-option label="按次收费" value="turn" />
            <el-option label="分段收费" value="partition" />
          </el-select>
        </el-form-item>
        <el-form-item label="计费规则" prop="ruleNameView">
          <el-input v-model="form.ruleNameView" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.rules .el-form-item {
  padding: 0 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}

.el-form-item__label {
  text-align: left; // 确保标签左对齐
}
</style>